package com.bh.shipment.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bh.common.enums.OrderStatus;
import com.bh.common.enums.ShipmentStatus;
import com.bh.common.exception.ServiceException;
import com.bh.common.utils.DateUtils;
import com.bh.common.utils.MathExtend;
import com.bh.common.utils.SecurityUtils;
import com.bh.kysys.domain.JcSysOrganization;
import com.bh.kysys.mapper.JcSysOrganizationMapper;
import com.bh.ledger.domain.JcLedgerDetail;
import com.bh.ledger.mapper.JcLedgerDetailMapper;
import com.bh.order.domain.JcLed;
import com.bh.order.domain.JcOrder;
import com.bh.order.domain.JcOrderProduct;
import com.bh.order.domain.JcOrderReceivingParty;
import com.bh.order.mapper.JcLedMapper;
import com.bh.order.mapper.JcOrderMapper;
import com.bh.order.mapper.JcOrderProductMapper;
import com.bh.order.mapper.JcOrderReceivingPartyMapper;
import com.bh.order.service.IJcOrderTrackService;
import com.bh.shipment.domain.JcBerthStand;
import com.bh.shipment.domain.JcShipment;
import com.bh.shipment.domain.JcVehicleArrive;
import com.bh.shipment.mapper.JcVehicleArriveMapper;
import com.bh.shipment.service.IJcBerthStandService;
import com.bh.shipment.service.IJcShipmentService;
import com.bh.shipment.service.IJcShipmentTrackService;
import com.bh.shipment.service.IJcVehicleArriveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 车辆到站Service业务层处理
 *
 * @author slx
 * @date 2023-04-24
 */

@Service
public class JcVehicleArriveServiceImpl extends ServiceImpl<JcVehicleArriveMapper, JcVehicleArrive> implements IJcVehicleArriveService {
    @Autowired
    private JcVehicleArriveMapper jcVehicleArriveMapper;

    @Autowired
    private IJcShipmentService jcShipmentService;

    @Autowired
    private IJcShipmentTrackService jcShipmentTrackService;

    @Autowired
    private IJcOrderTrackService jcOrderTrackService;

    @Autowired
    private IJcBerthStandService jcBerthStandService;

    @Autowired
    private JcLedMapper ledLedMapper;

    @Autowired
    private JcOrderMapper orderMapper;

    @Autowired
    private JcOrderReceivingPartyMapper orderReceivingPartyMapper;

    @Autowired
    private JcOrderProductMapper orderProductMapper;

    @Autowired
    private JcLedgerDetailMapper ledgerDetailMapper;

    @Autowired
    private JcSysOrganizationMapper organizationMapper;

    /**
     * 查询车辆到站
     *
     * @param id 车辆到站主键
     * @return 车辆到站
     */
    @Override
    public JcVehicleArrive selectJcVehicleArriveById(Long id) {
        return jcVehicleArriveMapper.selectById(id);
    }

    /**
     * 查询车辆到站列表
     *
     * @param jcVehicleArrive 车辆到站
     * @return 车辆到站
     */
    @Override
    public List<JcVehicleArrive> selectJcVehicleArriveList(JcVehicleArrive jcVehicleArrive) {
        return jcVehicleArriveMapper.selectJcVehicleArriveList(jcVehicleArrive);
    }

    @Override
    public List<JcVehicleArrive> selectJcVehicleArriveByShipmentId(Long jcShipmentId, Long nowOrgId) {
        return jcVehicleArriveMapper.selectJcVehicleArriveByShipmentId(jcShipmentId, nowOrgId);
    }

    /**
     * 新增车辆到站
     *
     * @param jcVehicleArrive 车辆到站
     * @return 结果
     */
    @Override
    public int insertJcVehicleArrive(JcVehicleArrive jcVehicleArrive) {
        jcVehicleArrive.setCreateTime(DateUtils.getNowDate());
        return jcVehicleArriveMapper.insert(jcVehicleArrive);
    }

    /**
     * 修改车辆到站
     *
     * @param jcVehicleArrive 车辆到站
     * @return 结果
     */
    @Override
    public int updateJcVehicleArrive(JcVehicleArrive jcVehicleArrive) {
        return jcVehicleArriveMapper.updateById(jcVehicleArrive);
    }

    /**
     * 批量删除车辆到站
     *
     * @param ids 需要删除的车辆到站主键
     * @return 结果
     */
    @Override
    public int deleteJcVehicleArriveByIds(Long[] ids) {
        return jcVehicleArriveMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除车辆到站信息
     *
     * @param id 车辆到站主键
     * @return 结果
     */
    @Override
    public int deleteJcVehicleArriveById(Long id) {
        return jcVehicleArriveMapper.deleteById(id);
    }

    /**
     * 到站操作： 两种情况构成：1、司机操作车辆到站 2、网点管理员扫码
     * 操作内容：
     * 1、更新车辆状态为到站
     * 2、更新车辆到站时间
     * 3、更新车辆到站网点
     *
     * @param jcShipmentIds
     * @return
     */
    @Override
    public int saveVehicleArrive(Long[] jcShipmentIds) {
        int num = 0;
        List<JcShipment> shipments = jcShipmentService.listByIds(Arrays.asList(jcShipmentIds));
        if (shipments == null || shipments.size() == 0) {
            throw new ServiceException("没有找到运单信息");
        }
        for (JcShipment shipment : shipments) {
            if (shipment.getStatus() != ShipmentStatus.DESPATCH.getValue()
                    && shipment.getStatus() == ShipmentStatus.DESPATCH_PART.getValue()
                    && shipment.getStatus() == ShipmentStatus.ARRIVE.getValue()
                    && shipment.getStatus() == ShipmentStatus.ARRIVE_PART.getValue()) {
                throw new ServiceException("运单已经到站");
            }
            // 原来是站点的人来判断是否到达，新规则变成 司机来判断
            JcSysOrganization organization = organizationMapper.selectById(shipment.getJcNextOrganizationId());
            if (organization == null) {
                organization = organizationMapper.selectById(shipment.getJcToOrganizationId());
            }
            JcVehicleArrive vehicleArrive;
            List<JcVehicleArrive> arrives = this.selectJcVehicleArriveByShipmentId(shipment.getId(), organization.getId());
            if (arrives != null && arrives.size() > 0) {
                vehicleArrive = arrives.get(0);
            } else {
                vehicleArrive = new JcVehicleArrive();
                vehicleArrive.setJcOrganizationId(organization.getId());
                vehicleArrive.setWhichStation(organization.getName());
                vehicleArrive.setArriveTime(shipment.getFactArriveTime());
                vehicleArrive.setCreateName(SecurityUtils.getUsername());
                vehicleArrive.setCreateTime(new Date());
                vehicleArrive.setJcShipmentId(shipment.getId());
                vehicleArrive.setVehicleTime(new Date());

                num += jcVehicleArriveMapper.insert(vehicleArrive);
            }

            // 如果是司机操作，则需要注释掉下面的判断代码，因为司机不一定是本站的人，只能通过 app 来提示判断，或者通过定位来判断
            if (shipment.getJcToOrganizationId().equals(organization.getId()) && shipment.getNextOrganization() != null) {
                //运抵
                shipment.setStatus(ShipmentStatus.ARRIVE.getValue());
                //运抵时间
                shipment.setFactArriveTime(vehicleArrive.getVehicleTime());
            } else {
                List<JcBerthStand> berthStands = jcBerthStandService.selectJcBerthStandListByShipmentId(shipment.getId());
                if (berthStands != null) {
                    for (JcBerthStand berthStand : berthStands) {
                        Long id = berthStand.getJcOrganizationId();
                        if (id.equals(shipment.getJcNextOrganizationId())) {
                            berthStand.setIsArrive(1);
                            jcBerthStandService.updateById(berthStand);
                            break;
                        }
                    }
                }
                //车辆到站
                shipment.setStatus(ShipmentStatus.VEHICLE_ARRIVE.getValue());
            }
            if (shipment.getJcNextOrganizationId() != null) {
                shipment.setJcNowOrganizationId(shipment.getJcNextOrganizationId());
                // 应该置为 null
                shipment.setJcNextOrganizationId(null);
            }
            //处理跟踪
            jcShipmentTrackService.addTrack(shipment.getId(), "车辆已经到达-" + organization.getName());
            List<JcLed> leds = shipment.getLeds();
            for (JcLed led : leds) {
                jcOrderTrackService.addTrack(led.getJcOrderId(), "您的分段单号:" + led.getCode() + "已经到达:" + organization.getName());
            }
           jcShipmentService.arriveJcShipmentList(shipment);
        }
        return num;
    }

    @Override
    public boolean saveShippingTime(JcVehicleArrive jcVehicleArrive) {
        JcShipment shipment = jcShipmentService.selectJcShipmentById(jcVehicleArrive.getJcShipmentId());
        List<JcBerthStand> berthStands = jcBerthStandService.selectJcBerthStandListByShipmentId(shipment.getId());
        if (berthStands != null && berthStands.size() > 0) {
            for (JcBerthStand berthStand : berthStands) {
                shipment.setJcOrganizationId(SecurityUtils.getOrgId());
                shipment.setJcNextOrganizationId(berthStand.getJcOrganizationId());
            }
        } else {
            shipment.setStatus(ShipmentStatus.DESPATCH.getValue());
            //修改分段运单状态
            List<JcLed> leds = shipment.getLeds();
            for (JcLed led : leds) {
                led.setStatus(OrderStatus.DESPATCH.getValue());
                led.setModifyTime(new Date());
                led.setModifyName(SecurityUtils.getUsername());
                ledLedMapper.updateById(led);
                //修改订单状态
                JcOrder order = new JcOrder();
                order.setId(led.getJcOrderId());
                order.setStatus(OrderStatus.DESPATCH.getValue());
                order.setModifyTime(new Date());
                order.setModifyName(SecurityUtils.getUsername());
                orderMapper.updateById(order);
            }
        }
        return jcShipmentService.updateById(shipment);
    }

    @Override
    public boolean saveArriveTime(JcVehicleArrive jcVehicleArrive) {
        JcShipment shipment = jcShipmentService.selectJcShipmentById(jcVehicleArrive.getJcShipmentId());
        shipment.setStatus(ShipmentStatus.ARRIVE.getValue());
        //修改分段运单状态
        List<JcLed> leds = shipment.getLeds();
        for (JcLed led : leds) {
            led.setStatus(OrderStatus.ARRIVE.getValue());
            ledLedMapper.updateById(led);
            //修改订单状态
            JcOrder order =  new JcOrder();
            order.setId(led.getJcOrderId());
            order.setStatus(OrderStatus.ARRIVE.getValue());
            order.setModifyTime(new Date());
            order.setModifyName(SecurityUtils.getUsername());
            orderMapper.updateById(order);
        }
        return jcShipmentService.updateById(shipment);
    }

    @Override
    public String getVehiclePrint(Long shipmentId) {
        JcShipment shipment = jcShipmentService.selectJcShipmentById(shipmentId);
        StringBuilder stringBuilder = new StringBuilder();
        Date factLeaveTime = shipment.getFactLeaverTime();
        String begin = "  <col width=43 style='mso-width-source:userset;mso-width-alt:1536;width:32pt'>\n" +
                " <col width=42 style='mso-width-source:userset;mso-width-alt:1479;width:31pt'>\n" +
                " <col width=61 style='mso-width-source:userset;mso-width-alt:2161;width:46pt'>\n" +
                " <col width=50 style='mso-width-source:userset;mso-width-alt:1792;width:38pt'>\n" +
                " <col width=59 style='mso-width-source:userset;mso-width-alt:2104;width:44pt'>\n" +
                " <col width=65 style='mso-width-source:userset;mso-width-alt:2304;width:49pt'>\n" +
                " <col width=86 style='mso-width-source:userset;mso-width-alt:3072;width:65pt'>\n" +
                " <col width=62 style='mso-width-source:userset;mso-width-alt:2218;width:47pt'>\n" +
                " <col width=51 style='mso-width-source:userset;mso-width-alt:1820;width:38pt'>\n" +
                " <col width=55 style='mso-width-source:userset;mso-width-alt:1962;width:41pt'>\n" +
                " <col width=57 style='mso-width-source:userset;mso-width-alt:2019;width:43pt'>\n" +
                " <col width=31 style='mso-width-source:userset;mso-width-alt:1109;width:23pt'>\n" +
                " <col width=48 style='mso-width-source:userset;mso-width-alt:1706;width:36pt'>\n" +
                " <col width=44 style='mso-width-source:userset;mso-width-alt:1564;width:33pt'>\n" +
                " <col width=75 style='mso-width-source:userset;mso-width-alt:2673;width:56pt'>\n" +
                " <tr height=37 style='mso-height-source:userset;height:27.6pt'>\n" +
                "  <td colspan=14 height=37 class=xl69 width=754 style='height:27.6pt;\n" +
                "  width:566pt'>货物配载清单</td>\n" +
                "  <td width=75 style='width:56pt'></td>\n" +
                " </tr>\n" +
                " <tr height=30 style='mso-height-source:userset;height:22.2pt'>\n" +
                "  <td colspan=2 height=30 class=xl80 style='height:22.2pt'>发车时间</td>\n" +
                "  <td colspan=2 class=xl76>" + factLeaveTime + "</td>\n" +
                "  <td class=xl81>车牌号：</td>\n" +
                "  <td class=xl77>" + shipment.getLicense() + "</td>\n" +
                "  <td class=xl82>司机：</td>\n" +
                "  <td class=xl78>" + shipment.getOutDriver() + "</td>\n" +
                "  <td class=xl79></td>\n" +
                "  <td class=xl83>电话：</td>\n" +
                "  <td colspan=3 class=xl76>" + shipment.getOutPhone() + "</td>\n" +
                "  <td class=xl78></td>\n" +
                "  <td class=xl66></td>\n" +
                " </tr>\n" +
                " <tr height=30 style='mso-height-source:userset;height:22.8pt'>\n" +
                "  <td height=30 class=xl72 style='height:22.8pt;border-top:none'>起运站</td>\n" +
                "  <td class=xl72 style='border-top:none;border-left:none'>到达站</td>\n" +
                "  <td class=xl72 style='border-top:none;border-left:none'>发货人</td>\n" +
                "  <td class=xl72 style='border-top:none;border-left:none'>原单号</td>\n" +
                "  <td class=xl72 style='border-top:none;border-left:none'>收货人</td>\n" +
                "  <td class=xl72 style='border-top:none;border-left:none'>电话</td>\n" +
                "  <td class=xl72 style='border-left:none'>地址</td>\n" +
                "  <td class=xl72 style='border-left:none'>货物</td>\n" +
                "  <td class=xl72 style='border-left:none'>件数</td>\n" +
                "  <td class=xl72 style='border-left:none'>重量</td>\n" +
                "  <td class=xl72 style='border-top:none;border-left:none'>体积</td>\n" +
                "  <td class=xl73 width=31 style='border-top:none;border-left:none;width:23pt'>交货方式</td>\n" +
                "  <td class=xl73 width=48 style='border-top:none;border-left:none;width:36pt'>到付款</td>\n" +
                "  <td class=xl72 style='border-left:none'>备注</td>\n" +
                "  <td class=xl67></td>\n" +
                " </tr>";

        stringBuilder.append(begin);
        //循环开始
        List<JcLed> leds = shipment.getLeds();
        String zhong = null;
        String shouhuoren = null;//收货人
        String fahuoren = null;//发货人
        String productName = null;//货名
        String lianxidianhua = null;//联系电话
        String shdizhi = null;//收货地址
        int number = 0;
        BigDecimal volume = BigDecimal.ZERO;
        BigDecimal weight = BigDecimal.ZERO;
        BigDecimal amount = BigDecimal.ZERO;//运费
        Integer znumber = 0;
        BigDecimal zvolume = BigDecimal.ZERO;
        BigDecimal zweight = BigDecimal.ZERO;
        BigDecimal arrivePay = BigDecimal.ZERO;//到付
        String jiaofufangshi = null;
        String formorg = shipment.getFromOrganization().getName().substring(0, 2);
        String toorg = shipment.getToOrganization().getName().substring(0, 2);
        if (leds.size() > 0) {
            int i = 0;
            for (JcLed led : leds) {
                JcOrder order = orderMapper.selectById(led.getJcOrderId());
                i = i + 1;
                Integer handoverType = order.getHandoverType();
                if (handoverType == 0) {
                    jiaofufangshi = "自提";
                } else {
                    jiaofufangshi = "送货";
                }
                List<JcOrderReceivingParty> orderReceivingParties = orderReceivingPartyMapper.selectJcOrderReceivingpartyListByOrderId(order.getId());
                // List<LedReceivingParty> ledReceivingParties = led.getLedReceivingParties();
                if (orderReceivingParties.size() > 0) {
                    for (JcOrderReceivingParty orderReceivingParty : orderReceivingParties) {
                        if (orderReceivingParty.getType() == 0) {
                            fahuoren = orderReceivingParty.getContactperson();
                        }
                        if (orderReceivingParty.getType() == 1) {
                            shouhuoren = orderReceivingParty.getContactperson();
                            shdizhi = orderReceivingParty.getDetaileAddress();
                            lianxidianhua = orderReceivingParty.getIphone();
                        }
                    }
                }
                List<JcOrderProduct> orderProducts = orderProductMapper.selectJcOrderProductListByOrderId(order.getId());
                // List<LedProduct> ledProducts = led.getLedProducts();
                if (orderProducts.size() > 0) {
                    for (JcOrderProduct orderProduct : orderProducts) {
                        productName = orderProduct.getName();
                        number = orderProduct.getNumber();
                        volume = orderProduct.getVolume();
                        weight = orderProduct.getWeight();
                        znumber += number;
                        zvolume = zvolume.add(volume);
                        zweight = zweight.add(weight);
                    }
                }
                List<JcLedgerDetail> ledgerDetails = ledgerDetailMapper.selectJcLedgerDetailListByOrderId(led.getId());
                for (JcLedgerDetail ledgerDetail : ledgerDetails) {
                    arrivePay = ledgerDetail.getArrivePay();
                }
                if (arrivePay == null) {
                    arrivePay = BigDecimal.ZERO;
                }
                String description = order.getDescription();//备注
                if (description == null) {
                    description = "";
                }
                zhong = " <tr height=18 style='height:13.8pt'>\n" +
                        "  <td height=18 class=xl70 width=43 style='height:13.8pt;border-top:none;width:32pt'>" + formorg + "</td>\n" +
                        "  <td class=xl70 width=42 style='border-top:none;border-left:none;width:31pt'>" + toorg + "</td>\n" +
                        "  <td class=xl70 width=61 style='border-top:none;border-left:none;width:46pt'>" + fahuoren + "</td>\n" +
                        "  <td class=xl70 width=50 style='border-top:none;border-left:none;width:38pt'>" + order.getRelateBill1() + "</td>\n" +
                        "  <td class=xl70 width=59 style='border-top:none;border-left:none;width:44pt'>" + shouhuoren + "</td>\n" +
                        "  <td class=xl70 width=65 style='border-top:none;border-left:none;width:49pt'>" + lianxidianhua + "</td>\n" +
                        "  <td class=xl70 width=86 style='border-top:none;border-left:none;width:65pt'>" + shdizhi + "</td>\n" +
                        "  <td class=xl70 width=62 style='border-top:none;border-left:none;width:47pt'>" + productName + "</td>\n" +
                        "  <td class=xl70 width=51 style='border-top:none;border-left:none;width:38pt'>" + number + "</td>\n" +
                        "  <td class=xl70 width=55 style='border-top:none;border-left:none;width:41pt'>" + weight + "</td>\n" +
                        "  <td class=xl70 width=57 style='border-top:none;border-left:none;width:43pt'>" + volume + "</td>\n" +
                        "  <td class=xl71 width=31 style='border-top:none;border-left:none;width:23pt'>" + jiaofufangshi + "</td>\n" +
                        "  <td class=xl71 width=48 style='border-top:none;border-left:none;width:36pt'>" + arrivePay + "</td>\n" +
                        "  <td class=xl71 width=44 style='border-top:none;border-left:none;width:33pt'>" + description + "</td>\n" +
                        "  <td class=xl68 width=75 style='width:56pt'></td>\n" +
                        " </tr>";
                stringBuilder.append(zhong);
            }
        }
        //循环结束
        double round = MathExtend.round(znumber, 2);
        BigDecimal round1 = zweight.setScale(2);
        BigDecimal round2 = zvolume.setScale(2);
        String end = "<tr height=18 style='height:13.8pt'>\n" +
                "  <td height=18 class=xl72 style='height:13.8pt;border-top:none'>合计</td>\n" +
                "  <td class=xl74 style='border-top:none;border-left:none'>　</td>\n" +
                "  <td class=xl74 style='border-top:none;border-left:none'>　</td>\n" +
                "  <td class=xl74 style='border-top:none;border-left:none'>　</td>\n" +
                "  <td class=xl74 style='border-top:none;border-left:none'>　</td>\n" +
                "  <td class=xl74 style='border-top:none;border-left:none'>　</td>\n" +
                "  <td class=xl74 style='border-top:none;border-left:none'>　</td>\n" +
                "  <td class=xl74 style='border-top:none;border-left:none'>　</td>\n" +
                "  <td class=xl75 style='border-top:none;border-left:none'>" + round + "</td>\n" +
                "  <td class=xl75 style='border-top:none;border-left:none'>" + round1 + "</td>\n" +
                "  <td class=xl75 style='border-top:none;border-left:none'>" + round2 + "</td>\n" +
                "  <td class=xl74 style='border-top:none;border-left:none'>　</td>\n" +
                "  <td class=xl74 style='border-top:none;border-left:none'>　</td>\n" +
                "  <td class=xl74 style='border-top:none;border-left:none'>　</td>\n" +
                "  <td></td>\n" +
                " </tr>\n" +
                " <tr height=126 style='height:96.6pt;mso-xlrowspan:7'>\n" +
                "  <td height=126 colspan=15 style='height:96.6pt;mso-ignore:colspan'></td>\n" +
                " </tr>\n" +
                " <tr height=18 style='height:13.8pt'>\n" +
                "  <td height=18 colspan=7 style='height:13.8pt;mso-ignore:colspan'></td>\n" +
                "  <td class=xl65></td>\n" +
                "  <td colspan=7 style='mso-ignore:colspan'></td>\n" +
                " </tr>\n" +
                " <![if supportMisalignedColumns]>\n" +
                " <tr height=0 style='display:none'>\n" +
                "  <td width=43 style='width:32pt'></td>\n" +
                "  <td width=42 style='width:31pt'></td>\n" +
                "  <td width=61 style='width:46pt'></td>\n" +
                "  <td width=50 style='width:38pt'></td>\n" +
                "  <td width=59 style='width:44pt'></td>\n" +
                "  <td width=65 style='width:49pt'></td>\n" +
                "  <td width=86 style='width:65pt'></td>\n" +
                "  <td width=62 style='width:47pt'></td>\n" +
                "  <td width=51 style='width:38pt'></td>\n" +
                "  <td width=55 style='width:41pt'></td>\n" +
                "  <td width=57 style='width:43pt'></td>\n" +
                "  <td width=31 style='width:23pt'></td>\n" +
                "  <td width=48 style='width:36pt'></td>\n" +
                "  <td width=44 style='width:33pt'></td>\n" +
                "  <td width=75 style='width:56pt'></td>\n" +
                " </tr>\n" +
                " <![endif]>";
        return stringBuilder.append(end).toString();
    }
}
